package com.bnz.cart.controller;

import com.bnz.cart.entity.group.Cart;
import com.bnz.cart.service.CartService;
import com.bnz.common.entity.R;
import org.bouncycastle.math.raw.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    // 1. 展示购物车页面
    @GetMapping({"/","cart.html"})
    public String cart(Model model,HttpSession session){
        // 1.1 得到登录名
        String name = (String) session.getAttribute("name");
        // 1.2 从redis中拿到购物车列表
        List<Cart> cartList = cartService.getCartList(name);
        // 1.3 将得到的购物车列表放到model中
        model.addAttribute("cartList",cartList);
        return "cart";
    }
    // 2. 将商品添加到购物车
    @GetMapping("/cart/add/{itemId}/{num}")
    public String addItem(@PathVariable String itemId, @PathVariable int num, HttpSession session, Model model){
        // 2.1 得到登录名，将以登录名为key，以购物车列表为值放在redis中
        String name = (String) session.getAttribute("name");
        // 2.2 添加商品到购物车列表，并最终以登录名为key，购物车列表为值放到redis中
        cartService.add(itemId,num,name);
        // 2.3 从redis中拿到购物车列表
        List<Cart> cartList = cartService.getCartList(name);
        // 2.3 将得到的购物车列表添加到model中
        model.addAttribute("cartList",cartList);
        return "cart";
    }
}
